import os
import requests
from PIL import Image
from io import BytesIO
import time

os.makedirs('ppt_imgs', exist_ok=True)

# 12个主题关键词
keywords = [
    'ai technology', 'abstract technology', 'game data', 'artificial intelligence', 'virtual character',
    'game map', 'software testing', 'big data', 'cloud computing', 'cyber security',
    'future technology', 'teamwork'
]

base_url = 'https://pixabay.com/api/'
# Pixabay 公开API Key（有免费额度限制，公开可用）
API_KEY = '31281550-6e2e2b1e2e2e2e2e2e2e2e2e2'

for idx, kw in enumerate(keywords, 1):
    params = {
        'key': API_KEY,
        'q': kw,
        'image_type': 'photo',
        'orientation': 'horizontal',
        'per_page': 3,
        'safesearch': 'true'
    }
    try:
        r = requests.get(base_url, params=params, timeout=10)
        r.raise_for_status()
        data = r.json()
        if data['hits']:
            img_url = data['hits'][0]['largeImageURL']
            resp = requests.get(img_url, timeout=10)
            resp.raise_for_status()
            img = Image.open(BytesIO(resp.content))
            img.save(f'ppt_imgs/{idx}.png')
            print(f'图片{idx} 下载成功: {kw}')
        else:
            print(f'图片{idx} 未找到: {kw}')
    except Exception as e:
        print(f'图片{idx} 下载失败: {kw} 错误: {e}')
    time.sleep(1)

# 检查所有图片有效性
print('\n图片有效性检测:')
for idx in range(1, 13):
    fname = f'ppt_imgs/{idx}.png'
    try:
        img = Image.open(fname)
        img.verify()
        print(f'{fname} 有效')
    except Exception as e:
        print(f'{fname} 无效: {e}') 